package com.smarty.net;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

public class ClientSll {
    public static void main(String[] args) throws IOException {
        System.setProperty("javax.net.debug", "SSL,handshake");
//        try {
//            SSLContext sslContext=SSLContext.getInstance("TLSv1.2");
////            try {
////                sslContext.init(null,null,null);
////            } catch (KeyManagementException e) {
////                e.printStackTrace();
////            }
        SSLSocketFactory socketFactory = null;
        try {
            socketFactory = SSLContext.getDefault().getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
//        Socket socket = new Socket("www.baidu.com", 443);
        SSLSocket socket = (SSLSocket)socketFactory.createSocket("www.baidu.com", 443);
//        socket.startHandshake();
        OutputStream outputStream = socket.getOutputStream();

        outputStream.write("GET / HTTP/1.1\r\n".getBytes(StandardCharsets.UTF_8));
        outputStream.write("HOST: www.baidu.com\r\n".getBytes(StandardCharsets.UTF_8));
        outputStream.write("Connection: close\r\n\r\n".getBytes(StandardCharsets.UTF_8));
        outputStream.flush();

        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream bytes=new ByteArrayOutputStream();
        int i;
        byte[] bytes1=new byte[10];
        while ((i = inputStream.read(bytes1))!=-1){
            bytes.write(bytes1,0,i);
        }
        System.out.println(bytes);
//        inputStream.close();
//        outputStream.close();
//        socket.close();

//            SSLEngine sslEngine = sslContext.createSSLEngine();
//            SocketFactory aDefault = SSLSocketFactory.getDefault();
//            Socket socket1 = aDefault.createSocket("www.baidu.com", 443);

//            Socket socket = new Socket("www.baidu.com", 443);
//            sslEngine.setUseClientMode(true);
//            sslEngine.beginHandshake();
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }

    }
}
